﻿using Infov1.Models;
using SqlSugar;
using System.Collections.ObjectModel;
using System.Windows.Input;
using HandyControl.Controls;
using Infov1.Commands;
using System;
using Infov1.Views;
using System.Windows;
using System.Diagnostics;
using System.Threading.Tasks;

namespace Infov1.ViewModels
{
    /// <summary>
    /// 客户信息管理 ViewModel
    /// 功能：客户信息的增删改查、分类筛选和搜索
    /// </summary>
    public class CustomerInfoViewModel : ViewModelBase
    {
        #region 私有字段
        private readonly ISqlSugarClient _db;
        // 数据集合
        private ObservableCollection<CustomerInfoModel> _customerList;
        private ObservableCollection<CustomerCategoryModel> _categoryList;
        private CustomerInfoModel _selectedCustomer;
        private CustomerCategoryModel _selectedCategory;

        // 状态标记
        private bool _isEditing;    // 编辑状态
        private bool _isNewMode;    // 新建模式
        private bool _isRunning;    // 加载状态
        private string _searchText; // 搜索文本
        #endregion

        #region 构造函数
        public CustomerInfoViewModel()
        {
            // 初始化数据库连接
            _db = DbContext.GetConnection();

            // 初始化命令
            LoadCustomerCommand = new RelayCommand(LoadCustomers);
            AddNewCommand = new RelayCommand(AddNew);
            EditCommand = new RelayCommand(StartEdit);
            DeleteCommand = new RelayCommand(Delete);
            SaveCommand = new RelayCommand(() => Save(SelectedCustomer));
            RefreshCommand = new RelayCommand(Refresh);
            SearchCommand = new RelayCommand(Search);

            // 初始化数据
            _isRunning = true;
       
        }
        #endregion

        #region 公共属性
        // 搜索相关
        public string SearchText
        {
            get => _searchText;
            set
            {
                _searchText = value;
                OnPropertyChanged(nameof(SearchText));
            }
        }

        // 分类相关
        public ObservableCollection<CustomerCategoryModel> CategoryList
        {
            get => _categoryList;
            set
            {
                _categoryList = value;
                OnPropertyChanged(nameof(CategoryList));
            }
        }

        public CustomerCategoryModel SelectedCategory
        {
            get => _selectedCategory;
            set
            {
                _selectedCategory = value;
                OnPropertyChanged(nameof(SelectedCategory));
                FilterCustomersByCategory();
            }
        }

        // 客户列表相关
        public ObservableCollection<CustomerInfoModel> CustomerList
        {
            get => _customerList;
            set
            {
                _customerList = value;
                OnPropertyChanged(nameof(CustomerList));
            }
        }

        public CustomerInfoModel SelectedCustomer
        {
            get => _selectedCustomer;
            set
            {
                _selectedCustomer = value;
                OnPropertyChanged(nameof(SelectedCustomer));
            }
        }

        // 状态属性
        public bool IsEditing
        {
            get => _isEditing;
            set
            {
                _isEditing = value;
                OnPropertyChanged(nameof(IsEditing));
            }
        }

        public bool IsRunning
        {
            get => _isRunning;
            set
            {
                _isRunning = value;
                OnPropertyChanged(nameof(IsRunning));
            }
        }
        //加载状态
        private bool _isLoading;
        public bool IsLoading
        {
            get => _isLoading;
            set
            {
                _isLoading = value;
                OnPropertyChanged();
            }
        }
        #endregion

        #region 命令定义
        public ICommand LoadCustomerCommand { get; }
        public ICommand AddNewCommand { get; }
        public ICommand EditCommand { get; }
        public ICommand DeleteCommand { get; }
        public ICommand SaveCommand { get; }
        public ICommand RefreshCommand { get; }
        public ICommand SearchCommand { get; }
        #endregion

        #region 数据加载方法
        /// <summary>
        /// 加载客户分类列表
        /// </summary>
        private void LoadCategories()
        {
            try
            {
                var categories = _db.Queryable<CustomerCategoryModel>()
                    .OrderBy(x => x.CategoryCode)
                    .ToList();

                // 添加"全部"选项到列表开头
                categories.Insert(0, new CustomerCategoryModel
                {
                    CategoryCode = "",
                    CategoryName = "全部"
                });

                CategoryList = new ObservableCollection<CustomerCategoryModel>(categories);
            }
            catch (Exception ex)
            {
                Growl.Error($"加载类别失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 加载客户列表
        /// </summary>
        private async Task LoadCustomersAsync()
        {
            if (_db == null) return;

            try
            {
                IsLoading = true;  // 显示加载状态

                var customers = await Task.Run(() =>
                {
                    return _db.Queryable<CustomerInfoModel>()
                        .Select(x => new CustomerInfoModel
                        {
                            Id = x.Id,
                            CustomerCode = x.CustomerCode,
                            CustomerCodeTd = x.CustomerCodeTd,
                            CompanyName = x.CompanyName,
                            ContactPerson = x.ContactPerson,
                            ContactPhone = x.ContactPhone,
                            CategoryCode = x.CategoryCode,
                            AreaCode = x.AreaCode,
                            Address = x.Address,
                            Notes = x.Notes,
                            CreationTime = x.CreationTime,
                            ModificationTime = x.ModificationTime
                        })
                        .Includes(x => x.Category)
                        .Includes(x => x.Area)
                        .OrderBy(x => x.CustomerCode)
                        .ToList();
                });

                Application.Current.Dispatcher.Invoke(() =>
                {

                    //重加载类别
                    LoadCategories();
                    CustomerList = new ObservableCollection<CustomerInfoModel>(customers);
                    IsEditing = false;
                    _isNewMode = false;
                    _isRunning = false;
                });
            }
            catch (Exception ex)
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    Growl.Error($"加载数据失败：{ex.Message}");
                });
            }
            finally
            {
                IsLoading = false;  // 隐藏加载状态
            }
        }
        #endregion
        // 调用客户加载（如果是在命令或其他方法中）
        public async void LoadCustomers()
        {
            await LoadCustomersAsync();
        }
        #region 搜索和筛选方法
        /// 搜索客户信息
        /// 支持客户编码、TD编码、公司名称的模糊查询
        private void Search()
        {
            if (string.IsNullOrWhiteSpace(SearchText))
            {
                LoadCustomers();
                //重加载类别
                LoadCategories();
                return;
            }

            try
            {
                var query = _db.Queryable<CustomerInfoModel>();

                // 添加模糊查询条件
                query = query.Where(x => x.CustomerCode.Contains(SearchText) ||
                                       x.CustomerCodeTd.Contains(SearchText) ||
                                       x.CompanyName.Contains(SearchText));

                // 添加分类筛选
                if (SelectedCategory != null && !string.IsNullOrEmpty(SelectedCategory.CategoryCode))
                {
                    query = query.Where(x => x.CategoryCode == SelectedCategory.CategoryCode);
                }

                ExecuteQuery(query);
            }
            catch (Exception ex)
            {
                Growl.Error($"搜索失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 根据选中分类筛选客户列表
        /// </summary>
        private void FilterCustomersByCategory()
        {
            try
            {
                var query = _db.Queryable<CustomerInfoModel>();

                // 添加分类筛选
                if (SelectedCategory != null && !string.IsNullOrEmpty(SelectedCategory.CategoryCode))
                {
                    query = query.Where(x => x.CategoryCode == SelectedCategory.CategoryCode);
                }

                // 保持搜索条件
                if (!string.IsNullOrWhiteSpace(SearchText))
                {
                    query = query.Where(x => x.CustomerCode.Contains(SearchText) ||
                                           x.CustomerCodeTd.Contains(SearchText) ||
                                           x.CompanyName.Contains(SearchText));
                }

                ExecuteQuery(query);
            }
            catch (Exception ex)
            {
                Growl.Error($"筛选失败：{ex.Message}");
            }
        }
        /// <summary>
        /// 执行查询并更新客户列表
        /// </summary>
        private void ExecuteQuery(ISugarQueryable<CustomerInfoModel> query)
        {
            var customers = query.Select(x => new CustomerInfoModel
            {   
                Id = x.Id,
                CustomerCode = x.CustomerCode,
                CustomerCodeTd = x.CustomerCodeTd,
                CompanyName = x.CompanyName,
                ContactPerson = x.ContactPerson,
                ContactPhone = x.ContactPhone,
                CategoryCode = x.CategoryCode,
                AreaCode = x.AreaCode,
                Address = x.Address,
                Notes = x.Notes,
                CreationTime = x.CreationTime,
                ModificationTime = x.ModificationTime
            })
            .Includes(x => x.Category)
            .Includes(x => x.Area)
            .OrderBy(x => x.CustomerCode)
            .ToList();

            CustomerList = new ObservableCollection<CustomerInfoModel>(customers);
        }
        #endregion

        #region 增删改操作方法
        /// <summary>
        /// 新增客户
        /// </summary>
        private void AddNew()
        {
            IsEditing = true;
            _isNewMode = true;
            SelectedCustomer = new CustomerInfoModel
            {
                CreationTime = DateTime.Now,
                ModificationTime = DateTime.Now
            };
            ShowEditDialog(SelectedCustomer);
        }

        /// <summary>
        /// 开始编辑客户信息
        /// </summary>
        private void StartEdit()
        {
            if (SelectedCustomer == null)
            {
                Growl.Warning("请选择要编辑的客户！");
                return;
            }

            IsEditing = true;
            _isNewMode = false;

            // 创建副本进行编辑
            var editCustomer = new CustomerInfoModel
            {
                Id = SelectedCustomer.Id,
                CustomerCode = SelectedCustomer.CustomerCode,
                CustomerCodeTd = SelectedCustomer.CustomerCodeTd,
                CompanyName = SelectedCustomer.CompanyName,
                ContactPerson = SelectedCustomer.ContactPerson,
                ContactPhone = SelectedCustomer.ContactPhone,
                CategoryCode = SelectedCustomer.CategoryCode,
                AreaCode = SelectedCustomer.AreaCode,
                Address = SelectedCustomer.Address,
                Notes = SelectedCustomer.Notes,
                ModificationTime = DateTime.Now
            };

            ShowEditDialog(editCustomer);
        }

        /// <summary>
        /// 删除客户
        /// </summary>
        private async void Delete()
        {
            try
            {
                // 1. 检查是否选中客户
                if (SelectedCustomer == null)
                {
                    Growl.Warning("请选择要删除的客户！");
                    return;
                }

                // 2. 确认删除
                var customerInfo = $"客户编码：{SelectedCustomer.CustomerCode}\n公司名称：{SelectedCustomer.CompanyName}";
                MessageBoxResult result = HandyControl.Controls.MessageBox.Show(
                    $"确定要删除以下客户吗？\n\n{customerInfo}",
                    "确认删除",
                    MessageBoxButton.YesNo,
                    MessageBoxImage.Warning);

                if (result != MessageBoxResult.Yes) return;

                // 3. 检查记录是否存在
                var existingCustomer = await _db.Queryable<CustomerInfoModel>()
                    .Where(x => x.CustomerCode == SelectedCustomer.CustomerCode)
                    .FirstAsync();

                if (existingCustomer == null)
                {
                    Growl.Warning("未找到要删除的客户记录！");
                    return;
                }

                // 4. 尝试删除
                // 方法1：直接删除
                var result1 = await _db.Deleteable(existingCustomer).ExecuteCommandAsync();

                if (result1 <= 0)
                {
                    // 方法2：使用主键删除
                    var result2 = await _db.Deleteable<CustomerInfoModel>()
                        .In(existingCustomer.Id)  // 假设CustomerCode是主键
                        .ExecuteCommandAsync();

                    if (result2 <= 0)
                    {
                        // 方法3：使用SQL语句直接删除
                        var result3 = await _db.Ado.ExecuteCommandAsync(
                            $"DELETE FROM CustomerInfo WHERE Id = @Id",
                            new { CustomerCode = existingCustomer.Id });

                        if (result3 <= 0)
                        {
                            Growl.Error("删除失败：无法删除记录");
                            return;
                        }
                    }
                }

                // 5. 删除成功后的处理
                Growl.Success("删除成功！");
                LoadCustomers();
                SelectedCustomer = null;
            }
            catch (Exception ex)
            {

                // 如果是外键约束错误，给出友好提示
                if (ex.Message.Contains("REFERENCE") || ex.Message.Contains("FK_"))
                {
                    Growl.Warning("无法删除：该客户存在关联数据，请先删除相关数据！");
                    return;
                }
                else
                {
                    // 详细的错误信息
                    var errorMessage = $"删除失败：{ex.Message}\n" +
                                      $"客户编码：{SelectedCustomer?.CustomerCode}\n" +
                                      $"异常类型：{ex.GetType().Name}\n" +
                                      $"堆栈跟踪：{ex.StackTrace}";

                    Growl.Error(errorMessage);
                    Debug.WriteLine(errorMessage);
                }
               
            }
        }

        /// <summary>
        /// 保存客户信息
        /// </summary>
        private void Save(CustomerInfoModel customer)
        {
            if (customer == null) return;

            try
            {
                if (_isNewMode)
                {
                    // 新增时检查编码是否存在
                    if (_db.Queryable<CustomerInfoModel>()
                        .Any(x => x.CustomerCode == customer.CustomerCode))
                    {
                        Growl.Warning("客户编码已存在！");
                        return;
                    }

                    _db.Insertable(customer).ExecuteCommand();
                    Growl.Success("新增成功！");
                }
                else
                {
                    var originalCode = SelectedCustomer.CustomerCode;

                    // 更新时如果修改了编码，检查新编码是否存在
                    if (originalCode != customer.CustomerCode)
                    {
                        if (_db.Queryable<CustomerInfoModel>()
                            .Any(x => x.CustomerCode == customer.CustomerCode))
                        {
                            Growl.Warning("新的客户编码已存在！");
                            return;
                        }
                    }
                    // 使用 Id 作为更新条件
                    _db.Updateable(customer)
                        .Where(x => x.Id == customer.Id)
                        .ExecuteCommand();
                    //检查编码
                   /* System.Windows.MessageBox.Show(originalCode);
                    System.Windows.MessageBox.Show(customer.CustomerCode);*/
                    Growl.Success("更新成功！");
                }

                LoadCustomers();
            }
            catch (Exception ex)
            {
                Growl.Error($"保存失败：{ex.Message}");
            }
        }
        #endregion

        #region 辅助方法
        /// <summary>
        /// 刷新数据
        /// </summary>
        private void Refresh()
        {
            LoadCustomers();
        
        }

        /// <summary>
        /// 显示编辑对话框
        /// </summary>
        private void ShowEditDialog(CustomerInfoModel customer)
        {
            var dialog = new CustomerEditDialog
            {
                DataContext = new CustomerEditViewModel(customer, _isNewMode)
            };

            if (dialog.ShowDialog() == true)
            {
                Save(dialog.Customer);
            }
        }
        #endregion
    }
}